import asyncio
from playwright.async_api import async_playwright, Request, Response
import logging
# 配置日志记录
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class CardActivatorAsync:
    def __init__(self):
        self.playwright = None
        self.browser = None
        self.page = None
        self.response_data = None

    async def start(self):
        try:
            self.playwright = await async_playwright().start()
            self.browser = await self.playwright.chromium.launch(headless=False, slow_mo=2000)
            self.page = await self.browser.new_page()

            # 设置请求和响应的回调
            self.page.on("request", self.on_request)
            self.page.on("response", self.on_response)
        except Exception as e:
            logger.error("Error during start: %s", e)
            await self.close()

    def on_request(self, request: Request) -> None:
        pass

    async def on_response(self, response: Response) -> None:
        if "activate-gift-coupon" in response.url:
            logger.info("response status %s", response.status)
            content_type = response.headers.get("content-type")
            logger.info("response content-type %s", content_type)
            logger.info("url----> %s", response.url)
            if response.status == 200 and content_type and "application/json" in content_type:
                try:
                    self.response_data = await response.json()
                    logger.info("response json %s %s",
                                self.response_data, type(self.response_data))
                except Exception as e:
                    logger.error("Error parsing JSON response: %s", e)
                    self.response_data = None
            else:
                self.response_data = await response.text()
                logger.info("response text %s", self.response_data)

    async def activate_card(self, name: str, mobile: str, id_number: str, code: str):
        # 确保 self.page 已经被初始化
        if self.page is None:
            raise RuntimeError(
                "Page is not initialized. Please call start() method first.")
        url = f'''
        https://gljm.ytsjq.com/wapmall/index.html?m_code=dwr1Op9C3C5qVSng3ZWSFA#/pages/preview/preview?id={code}&type=5
        '''
        try:
            await self.page.goto(url)
            logger.info("访问url: %s", url)
            logger.info("表单填写")
            await self.page.locator(':text("我已知晓")').click()
            await self.page.locator("input").nth(0).fill(name)
            await self.page.locator("input").nth(1).fill(id_number)
            await self.page.locator("input").nth(2).fill(mobile)
            logger.info("提交激活")
            await self.page.locator(':text("立即激活")').click()
        except Exception as e:
            logger.error("Error during card activation: %s", e)

    async def close(self):
        if self.browser is not None:
            await self.browser.close()
        if self.playwright is not None:
            await self.playwright.stop()

    def get_response_data(self):
        return self.response_data

    async def test(self):
        if self.page is None:
            raise RuntimeError(
                "Page is not initialized. Please call start() method first.")
        await self.page.goto("https://h5.zhoukezhang.com/workbench")



if __name__ == "__main__":
    card_activator = CardActivatorAsync()

    async def main():
        await card_activator.start()
        await card_activator.activate_card("尤伟", "15136107396", "410305196507294514", "1a81f073643813cbfc8102ccb388441e")
        # await card_activator.test()
        response_data = card_activator.get_response_data()
        print("Response Data:", response_data)
        await card_activator.close()
    # 使用 asyncio.run 来运行异步主函数
    asyncio.run(main())
